package com.dudy.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @program: zhuguangDemo
 * @description:
 * @ChannelHandler.Sharable 多环境下线程安全
 * ChannelInboundHandlerAdapter：
 * 处理适配器，用来操作ChannelInboundHandlerAdapter类型的每一步骤的控制流转
 * 实现ChannelInboundHandlerAdapter，该类提供了三种方法
 * 起到的也是逻辑流程的精确控制
 * ChannelFuture返回（具体你自己有没有完成），确定下一步
 * @author: dudy
 * @create: 2018-04-12 01:02
 **/
@ChannelHandler.Sharable
public class EcoClientHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(EcoClientHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ctx.writeAndFlush(Unpooled.copiedBuffer("QUERY TIME ORDER",
                CharsetUtil.UTF_8));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        logger.info("客户端：" + ctx.channel().localAddress()+"服务端："+ctx.channel().remoteAddress());
        ByteBuf result = (ByteBuf) msg;
        byte[] result1 = new byte[result.readableBytes()];
        result.readBytes(result1);
        System.out.println("Server said:" + new String(result1));
        result.release();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
                                Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

